package pri.lt.parser;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import pri.lt.Constants;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SogouWeixinParser implements Parser {

    static SogouWeixinParser sInstance;

    public synchronized static Parser getInstance() {
        if (sInstance == null) {
            sInstance = new SogouWeixinParser();
        }
        return  sInstance;
    }


    @Override
    public ParserResult parse(String url) {
        WebDriverWrapper webDriverWrapper = WebDriverManager.getWebDriverWrapper();
        try {
            String publishTime = null;

            webDriverWrapper.getWebDriver().get(url);

            //webDriverWrapper.scroll(10000);

            String pageXml = webDriverWrapper.getHtmlExcuteJs();//直接将加载完成的页面转换成xml格式的字符串
            Document doc = Jsoup.parse(pageXml);

            Object publishTimeObject = null;



            String srcTimeText = doc.getElementById("publish_time").text();
            try {
                long publishTimeMillins = System.currentTimeMillis();
                if ("今天".equals(srcTimeText)) {

                } else if ("昨天".equals(srcTimeText)) {
                    publishTimeMillins -= 24 * 60 * 60 * 1000;
                } else if ("前天".equals(srcTimeText)) {
                    publishTimeMillins -= 2 * 24 * 60 * 60 * 1000;
                } else if (srcTimeText.contains("天前")) {
                    String publishElapseDayString = publishTime.substring(0, publishTime.indexOf("天前"));
                    int publishElapseDay = Integer.parseInt(publishElapseDayString);
                    publishTimeMillins -= publishElapseDay * 24 * 60 * 60 * 1000;
                }
                Date date = new Date(publishTimeMillins);
                publishTime = new SimpleDateFormat(Constants.DATETIME_FORMAT).format(date);
            } catch (Exception e) {

            }

            if (publishTime == null || publishTime.trim().length() == 0) {

                webDriverWrapper.release();
                return null;
            }

            System.out.println("litao url publish at " + publishTime);

            Element contentElement = doc.selectFirst("div.rich_media_content");
            if (contentElement == null) {
                webDriverWrapper.release();
                return null;
            }

            Elements imageElements = contentElement.select("img[data-src]");//获取到的值为所有的<img src="...">
            if (imageElements != null) {
                for (Element element : imageElements) {

                    String imgUrl = element.attr("data-src");//获取到src的值
                    element.attr("src", imgUrl);
                    element.attr("height", "auto");
                }
            }


            String cleanXml = Jsoup.clean(contentElement.html(), Whitelist.basicWithImages());
            String title = null;
            try {
                Element titleElement = doc.getElementById("activity-name");
                title = titleElement.text();
            } catch (Exception e) {

            }
            ParserResult parserResult = new ParserResult();

            parserResult.title = title;
            parserResult.content = contentElement.html();
            //parserResult.allHtml = pageXml;
            try {
                parserResult.publishTime = new SimpleDateFormat(Constants.DATETIME_FORMAT).parse(publishTime);

            } catch (Exception e) {

                e.printStackTrace();
            }


//            try {
//                WebElement commentLinkElement = webDriverWrapper.getWebDriver().findElement(By.id("cmtLink"));
//                parserResult.commentUrl = commentLinkElement.getAttribute("href");
//            } catch (NoSuchElementException e) {
//                try {
//                    webDriverWrapper.getWebDriver().switchTo().frame("commentIframe");
//                    WebElement commentLinkElement = webDriverWrapper.getWebDriver().findElement(By.id("cmtLink"));
//                    parserResult.commentUrl = commentLinkElement.getAttribute("href");
//                } catch (Exception e2) {
//                    System.out.println("get comment link exception " + url);
//                    System.out.println("getHotCommentResult get Exception pagehtml = " + pageXml);
//                    webDriverWrapper.release();
//                }
//            } catch (Exception e) {
//                System.out.println("get comment link exception " + url);
//                System.out.println("getHotCommentResult get Exception pagehtml = " + pageXml);
//                return null;
//            } finally {
//
//                webDriverWrapper.release();
//            }

            Elements elements = contentElement.select("img[src]");//获取到的值为所有的<img src="...">

            int i = 0;
            for (Element element : elements) {
                try {

                    String imgUrl = element.attr("data-src");//获取到src的值
                    if (imgUrl != null) {
                        if (imgUrl.startsWith("http")) {

                        } else {
                            if (url.startsWith("https")) {
                                imgUrl = "https:" + imgUrl;
                            } else if (url.startsWith("http")) {
                                imgUrl = "http:" + imgUrl;
                            }
                        }
                        URL imgHttpUrl = new URL(imgUrl);
                        URLConnection connection = imgHttpUrl.openConnection();
                        connection.setDoOutput(true);
                        BufferedImage image = ImageIO.read(connection.getInputStream());
                        int srcWidth = image .getWidth();      // 源图宽度
                        int srcHeight = image .getHeight();    // 源图高度

                        if (srcWidth > 0 && srcHeight > 0 && srcWidth >= 500) {
                            float radio = ((float)srcHeight) / ((float)srcWidth);
                            if (radio > 0.25 && radio <= 2) {
                                parserResult.thumbnailUrl = imgUrl;
                                break;
                            }
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }



            if (!parserResult.isValid()) {
                webDriverWrapper.release();
                return null;
            }


            return parserResult;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            webDriverWrapper.release();
        }
        return null;
    }

    @Override
    public HotCommentResult getHotCommentResult(String url, ParserResult parserResult) {
        HotCommentResult hotCommentResult = new HotCommentResult();
        hotCommentResult.isHot = true;
        return hotCommentResult;
    }

    @Override
    public boolean isDomainSupport(String url) {
        return url != null
        && (url.contains("weixin.sogou.com/pcindex") || url.contains("mp.weixin.qq.com/s?"));
    }

    @Override
    public boolean isUrlCanParse(String url) {
        return url != null && url.contains("mp.weixin.qq.com/s?");
    }

    @Override
    public boolean isDomainDirectory(String url) {
        return url != null && url.contains("weixin.sogou.com/pcindex");
    }

}
